package com.zzu.base.handler;

import com.zzu.base.common.pojo.LoginUser;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import org.springframework.security.core.GrantedAuthority;
import java.io.Serializable;
import java.util.Collection;

@Component
public class PermissionHandler implements PermissionEvaluator {
    @Override
    public boolean hasPermission(Authentication auth, Object target, Object permission) {
        if (auth == null || permission == null) {
            return false;
        }

        LoginUser loginUser = (LoginUser) auth.getPrincipal();
        Collection<? extends GrantedAuthority> authorities = loginUser.getAuthPermissions();

        if (hasAuthority(authorities, "permit_all")) {
            return true;
        }

        // 处理其他权限（兼容 hasRole 表达式）
        String permissionString = permission.toString();
        return hasAuthority(authorities, permissionString);
    }

    @Override
    public boolean hasPermission(Authentication auth, Serializable targetId, String targetType, Object permission) {
        return hasPermission(auth, null, permission);
    }

    // 辅助方法：检查是否拥有某个权限
    private boolean hasAuthority(Collection<? extends GrantedAuthority> authorities, String authority) {
        if (authorities == null) {
            return false;
        }
        return authorities.stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(a -> a.equals(authority));
    }
}